// pages/login/login.js
const app = getApp();
var myShowToast = require('../../template/toast/showToast');//引入消息提醒暴露的接口  
var myUtils = require('../../utils/util');//引入消息提醒暴露的接口  
import httpsUtils from '../../utils/https.js';


Page({

  /**
   * 页面的初始数据
   */
  data: {
    hint: '请输入手机号',
    result: '',
    codeResult: '',
    codeHint: '请输入验证码',
    verifyCodeTime2: '获取验证码',
    buttonDisable: false,
    phoneCode: '',
    backStep: 1,
    isTab:false,
    password:'',
    password2:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      backStep: options.backStep,
      isTab: options.isTab,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //事件函数
  /* 手机号输入框 */
  bindInputBlur: function (e) {
    var that = this;
    var PhoneReg = new RegExp('^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$');
    var phones = PhoneReg.exec(e.detail.value);

    if (myUtils.isMobile(e.detail.value)) {
      that.setData({
        result: e.detail.value,
        hint: '请输入手机号'
      })
    } else {
      that.setData({
        result: '',
        hint: '手机号有误，请重新输入'
      })
    }
  },

  /**
   * 密码输入
   */
  bindPassword: function (e) {
    var that = this;

    if (myUtils.isPasword(e.detail.value)) {
      that.setData({
        password: e.detail.value
      })
    } else {
      myShowToast.showToast({ title: '密码输入格式错误，请输入6到20位字母数字组合' });
    }
  },

  /**
   * 密码输入
   */
  bindPassword2: function (e) {
    var that = this;

    if (e.detail.value == that.data.password) {
      that.setData({
        password2: e.detail.value
      })
    } else {
      myShowToast.showToast({ title: '两次密码输入不一致，请重新输入' });
    }
  },

  /**
   * 获取验证码
   */
  getPhoneCode: function (e) {
    var that = this;
    that.setData({
      phoneCode: e.detail.value
    })
  },
  //获取验证码
  resetCode: function (e) {
    var that = this;
    setTimeout(function(){
      var PhoneReg = new RegExp('^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$');
      var phoneOk = PhoneReg.exec(that.data.result);
      if (!myUtils.isMobile(that.data.result)) {
        myShowToast.showToast({ title: '请输入的正确手机号' });
        return false;
      }

      if (that.data.buttonDisable) return false;
      var c = 88;
      var intervalId = setInterval(function () {
        c = c - 1;
        that.setData({
          verifyCodeTime2: c + 's后重发',
          buttonDisable: true
        })
        if (c == 0) {
          clearInterval(intervalId);
          that.setData({
            verifyCodeTime2: '获取验证码',
            buttonDisable: false
          })
        }
      }, 1000)

      var phones = that.data.result;
      wx.showToast({
        title: phones,
      })

      wx.request({
        url: app.globalData._url + '/user/getPhoneCode',
        method: 'get',
        header: {
          'content-type': 'application/json;charset=UTF-8'
        },
        data: {
          phone: phones,
          type: 1
        },
        success: function (res) {
        }
      })

    },1000)
  },

  bindVeriCode: function (e) {
    var that = this;
    that.setData({
      codeResult: e.detail.value,
    })
  },

  /**
   * 开始注册
   */
  startRegister: function (wxUserInfo, code) { 
    wx.showToast({
      title: '注册中...',
      icon: 'loading'
    })
    setTimeout(function () {
      wx.hideToast()
    }, 10000)
    var that = this;
    httpsUtils.postData({
      _url: app.globalData._url + '/user/bindPhone',
      data: {
        code: code,
        iv: wxUserInfo.iv,
        encryptedData: wxUserInfo.encryptedData,
        phone: that.data.result,
        phoneCode: that.data.phoneCode,
        userName: wxUserInfo.userInfo.nickName,
        headImg: wxUserInfo.userInfo.avatarUrl,
        password: that.data.password
      },
    }, function (json) {
      if (json.success) {
        wx.hideToast();
        wx.setStorageSync('userInfo', json.data);
        wx.setStorageSync('utoken', json.data.token);
        app.globalData.token = json.data.token;

        if (that.data.isTab || that.data.isTab == 'true'){
          var delta = parseInt(that.data.backStep);
          wx.navigateBack({
            delta: delta,
            success: function () {
              wx.showToast({
                title: '注册登陆成功',
              })
            },
          })
        }else{
          wx.switchTab({
            url: '../myinfo/myinfo',
            success: function () {
              wx.showToast({
                title: '注册登陆成功',
              })
            },
          })
        }
        
      } else {
        myShowToast.showToast({ title: json.msg });
      }
    })
  },

  /**
   * 提交
   */
  formSubmit: function (e) {
    var that = this;

    const client_phone = that.data.result;
    const veri_code = that.data.phoneCode;
    const password = that.data.password;
    const password2 = that.data.password2;

    if (!myUtils.isMobile(client_phone)) {
      myShowToast.showToast({ title: '请输入正确手机号' });
      return false;
    }

    if (myUtils.isBlank(password)) {
      myShowToast.showToast({ title: '密码不能为空' });
      return false;
    }

    if (password != password2) {
      myShowToast.showToast({ title: '两次密码不一致' });
      return false;
    }

    if (myUtils.isBlank(veri_code)) {
      myShowToast.showToast({ title: '验证码为空' });
      return false;
    }

    wx.login({
      success: function (res) {
        var code = res.code;
        wx.getUserInfo({
          success: function (res) {
            that.startRegister(res, code);
          }
        })
      }
    })
  }

})
//export default login;